using System;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;
using log4net;

namespace Sedna.Core.Controller.Configurations
{
	/// <summary>
	/// Summary description for EnumStringDataParser.
	/// </summary>
	public class EnumStringDataParser : IDataTranslator
	{
		private ILog log=LogManager.GetLogger(typeof(EnumStringDataParser));

		private Type enumType;
		private object defaultValue;
		private bool ignoreCase=true;
        private Type toType = null;

		public bool IgnoreCase
		{
			get { return ignoreCase; }
			set { ignoreCase = value; }
		}

		public Type EnumType
		{
			get { return enumType; }
			set { enumType = value; }
		}

		public object DefaultValue
		{
			get { return defaultValue; }
			set { defaultValue = value; }
		}

	    public Type ToType
	    {
	        set { toType = value; }
	    }

	    public object Translate(Control control, object value)
		{            	        
			return Translate(control, value, null);
		}

		public object Translate(Control control, object value, Type targetType)
		{
			if (enumType==null)
			{
				if (defaultValue==null||!defaultValue.GetType().IsSubclassOf(typeof(System.Enum)))
				{
					string errorMessage="EnumType is not specified. EnumType cannot be obtained from default value.";
					log.Error(errorMessage);
					throw new ControllerConfigurationException(errorMessage);
				}

				enumType=defaultValue.GetType();
			}

			string parseString=value as string;
			if (parseString==null||parseString.Trim().Equals(String.Empty))
			{
				return defaultValue;
			}

			try
			{
                if (Enum.IsDefined(enumType, parseString))
                {
                    if (toType == null)
                        return System.Enum.Parse(enumType, parseString, ignoreCase);
                    else
                        return Convert.ChangeType(System.Enum.Parse(enumType, parseString, ignoreCase), toType);
                }
                else
                    return (toType == null) ? defaultValue : Convert.ChangeType(defaultValue, toType);
			}
			catch
			{
				if (log.IsDebugEnabled)
				{
					log.Debug("Parsing exception was thrown. Use default value: "+defaultValue);
				}
				return defaultValue;
			}
		}
	}
}
